const TImageineDesign = require('../../orm/model/TImageineDesign')
const oss = require('../../lib/oss')
const axios = require('axios').default
const dayjs = require('dayjs')
const {baseUrl} = require('../../env')
const uploadFiles = async (images, id) => {
  const files = [];
  for (let i = 0; i < images.length; i++) {
    const fileName = `text2image/${dayjs().format(
      "YYYY-MM-DD"
    )}/${id}-${i}.png`;
    // fs.writeFileSync('./t'+i+'.txt',images[i])
    const buffer = Buffer.from(images[i], "base64");

    await oss.put(fileName, buffer);
    files.push(fileName);
  }

  return files.join(",");
};
const img2Img =  (data) => {
  console.log('图生图啊')
  return new Promise((resolve, reject) => {
    console.log('没进来啊',axios)
    axios({
      timeout: 99999999,
      // url:`http://172.20.21.185:7860/sdapi/v1/txt2img`,
      url: `${baseUrl}/sdapi/v1/img2img`,
      method: "POST",
      data: JSON.parse(data.params),
    })
      .then(res => res.data)
      .then(async (res) => {
        console.log("成功了啊")
        const { images = [] } = res;
        const files = await uploadFiles(images, data.id);
        await TImageineDesign.update(
          {
            output: JSON.stringify({ images: files }),
          },
          { taskId: data.id }
        );
        resolve({
          images: files,
        });
      })
      .catch((error) => {
        console.log("错误了啊")
        reject(error);
      });
  });
};

module.exports = img2Img;
